package switchviz.graphic.gauge;

import java.util.Iterator;

import org.jdom.Element;

import switchviz.core.view.ViewTree;

public class GaugePersistence 
{
	public static final String SCALE = "scale";
	public static final String MULTIPORT = "multiport";
	public static final String PORT = "port";
	protected Element _root = null;
	
	public Element getElement()
	{
		return _root;
	}
	
	public void setElement(Element root)
	{
		_root = root;
	}
	
	public Element getScaleElement()
	{
		Element scalenode = null;
		if(_root.getChild(SCALE) == null)
		{
			scalenode = new Element(SCALE);
			_root.addContent(scalenode);
		}
		else
		{
			scalenode = _root.getChild(SCALE);
		}
		return scalenode;
	}
	
	protected void getElement(GaugeDataModel datamodel)
	{
		_root.setAttribute(ViewTree.GAUGEATTNAME, datamodel.getName());
		addNode(PORT, String.valueOf(datamodel.getPort()));
		if(datamodel.isMultiplePerPort())
			addNode(MULTIPORT, "1");
		else
			addNode(MULTIPORT, "0");
	}
	
	public static Element setMultiplePerPorts(Element node, boolean value, int port)
	{
		if(value)
		{
			node.getChild(MULTIPORT).setText("1");
			node.getChild(PORT).setText("0");
		}
		else
		{
			node.getChild(MULTIPORT).setText("0");
			node.getChild(PORT).setText(String.valueOf(port));
			
			if(node.getChild("signallist") != null)
			{		
				Iterator<?> iter = node.getChild("signallist").getChildren().iterator();
				
				while (iter.hasNext())
				{
					Element child = ((Element)iter.next()).getChild(PORT);
					
					if (child != null)
						child.setText(String.valueOf(port));
				}
			}
		}
		return node;
	}
	
	protected void setDataModel(GaugeDataModel datamodel)
	{
		datamodel.setName(_root.getAttributeValue(ViewTree.GAUGEATTNAME));
		datamodel.setType(_root.getAttributeValue(ViewTree.GAUGEATTTYPE));
		if(_root.getChild(PORT) != null)
			datamodel.setPort(Integer.valueOf(_root.getChildText(PORT)));
		if(_root.getChild(MULTIPORT) != null)
		{
			int choice = Integer.valueOf(_root.getChildText(MULTIPORT));
			if(choice == 0)
				datamodel.setMultiplePerPort(false);
			else
				datamodel.setMultiplePerPort(true);
		}
		
	}
	
	protected void addNode(String nodename, String value)
	{
		if(_root.getChild(nodename) != null)
			_root.getChild(nodename).setText(value);
		else
			_root.addContent(new Element(nodename).setText(value));
	}
}
